package com.sky.service.impl;

import com.sky.constant.MessageConstant;
import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkspaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description 数据统计
 * @Author liuqiang
 * @Date 2024/3/1
 */
@Service
@Slf4j
public class ReportServiceImpl implements ReportService {
    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private WorkspaceService workspaceService;

    /**
     * 营业额统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {
        //根据传入的起始时间和结束时间得到时间的天数存入TurnoverReportVO的dateList
        List<LocalDate> dateList = getDateList(begin,end);
        //循环便利dateList得到每一天的日期，根据这个日期进行sql查询每一天的营业额，即每一天的订单状态为5的sum(amount)
        List<Double> turnoverList = new ArrayList<>();
        //select sum(amount) from orders where status = 5 and order_time >= 这天的最小时间值 and order_time <= 这天的最大时间值
        for (LocalDate date : dateList){
            //由于数据库中的数据是LocalDateTime，需要转换
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //将三个数据组成map当初参数传输
            Map map = new HashMap();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            map.put("status", Orders.COMPLETED);

            Double turnover = ordersMapper.getOrdersSum(map);
            turnover = turnover == null ? 0.0 : turnover;
            turnoverList.add(turnover);
        }
        //将结果封装TurnoverReportVO并返回
        return TurnoverReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .turnoverList(StringUtils.join(turnoverList,","))
                .build();
    }

    /**
     * 用户统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        //获取起始时间到终止时间之间的每一天的集合
        List<LocalDate> dateList = getDateList(begin,end);
        //遍历dateList查询每一天的用户总量和每一天新增用户
        List<Integer> userCountList = new ArrayList<>();
        List<Integer> newCountList = new ArrayList<>();
        for (LocalDate date : dateList){
            //由于数据库中的数据是LocalDateTime，需要转换
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            //每一天的用户总量：select count(*) from user where create_time <= endTime
            Integer userCount = userMapper.getUserCount(null,endTime);
            //每一天新增用户: select count(*) from user where create_time >= beginTime and create_time <= endTime
            Integer newCount= userMapper.getUserCount(beginTime,endTime);

            userCountList.add(userCount);
            newCountList.add(newCount);
        }
        return UserReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .totalUserList(StringUtils.join(userCountList,","))
                .newUserList(StringUtils.join(newCountList,","))
                .build();
    }

    /**
     * 订单统计
     * @param begin
     * @param end
     * @return
     */
    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        //获取起始时间到终止时间之间的每一天的集合
        List<LocalDate> dateList = getDateList(begin,end);
        //每日订单数
        List<Integer> orderCountList = new ArrayList<>();
        //每日有效订单数
        List<Integer> validOrderCountList = new ArrayList<>();
        for (LocalDate date : dateList){
            //由于数据库中的数据是LocalDateTime，需要转换
            LocalDateTime beginTime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endTime = LocalDateTime.of(date, LocalTime.MAX);
            Map map = new HashMap();
            map.put("beginTime",beginTime);
            map.put("endTime",endTime);
            //获取每日订单数orderDayCount:select count(*) from orders where order_time >=beginTime and order_time <= endTime
            Integer orderDayCount = ordersMapper.getOrdersCount(map);
            //每日有效订单数validDayOrderCount:select count(*) from orders where status = 5 and order_time >=beginTime and order_time <= endTime
            map.put("status", Orders.COMPLETED);
            Integer validDayOrderCount = ordersMapper.getOrdersCount(map);

            orderCountList.add(orderDayCount);
            validOrderCountList.add(validDayOrderCount);
        }
        //时间区间内的订单总数totalOrderCount:每日订单数的和
        Integer totalOrderCount = orderCountList.stream().reduce(Integer::sum).get();
        //时间区间内的有效订单数validOrderCount:每日有效订单数的和
        Integer validOrderCount = validOrderCountList.stream().reduce(Integer::sum).get();
        //订单完成率:有效订单数/订单总数
        Double orderCompletionRate = 0.0;
        //避免除数为0出现算术异常
        if (totalOrderCount != 0){
            //将 validOrderCount 对象转换为双精度浮点型数据，以便进行除法运算
            orderCompletionRate = validOrderCount.doubleValue() / totalOrderCount;
        }
        //封装数据并返回
        return OrderReportVO.builder()
                .dateList(StringUtils.join(dateList,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    /**
     * 查询销量排名top10
     * @param begin
     * @param end
     * @return
     */
    @Override
    public SalesTop10ReportVO getSalesTop10(LocalDate begin, LocalDate end) {
        //销量排行：在时间内状态为已完成且商品数量最多的前10个商品
        LocalDateTime beginTime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endTime = LocalDateTime.of(end, LocalTime.MAX);

        Map map = new HashMap();
        map.put("beginTime",beginTime);
        map.put("endTime",endTime);
        map.put("status", Orders.COMPLETED);

        List<GoodsSalesDTO> goodsSalesDTOList = ordersMapper.getSalesTop10(map);
        //获得商品名称集合
        List<String> nameList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getName).collect(Collectors.toList());
        //获得商品销量集合
        List<Integer> numberList = goodsSalesDTOList.stream().map(GoodsSalesDTO::getNumber).collect(Collectors.toList());
        //封装数据并返回
        return SalesTop10ReportVO.builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    /**
     * 导出近30天的运营数据报表
     * @param response
     */
    @Override
    public void exportBusinessData(HttpServletResponse response) {

        LocalDate begin = LocalDate.now().minusDays(30);
        LocalDate end = LocalDate.now().minusDays(1);
        //查询概览运营数据，提供给Excel模板文件
        BusinessDataVO businessData = workspaceService.getBusinessData(LocalDateTime.of(begin,LocalTime.MIN), LocalDateTime.of(end, LocalTime.MAX));
        //获取近30天的时间2022-05-28至2022-06-26
        String dateStr = "时间：" + begin + "至" + end;
        //获取表，使用类加载器
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        log.info("inputStream:{}",inputStream);
        ServletOutputStream out = null;
        XSSFWorkbook excel = null;
        try {
            //根据类加载器获得的InputStream加载模板文件对象
            excel = new XSSFWorkbook(inputStream);
            //获取表对象
            XSSFSheet sheet = excel.getSheetAt(0);
            //获取行对象
            XSSFRow row1 = sheet.getRow(1);
            //写入时间
            row1.getCell(1).setCellValue(dateStr);
            //写入概览数据
            XSSFRow row3 = sheet.getRow(3);
            XSSFRow row4 = sheet.getRow(4);
            //营业额
            row3.getCell(2).setCellValue(businessData.getTurnover());
            //订单完成率
            row3.getCell(4).setCellValue(businessData.getOrderCompletionRate());
            //新增用户数
            row3.getCell(6).setCellValue(businessData.getNewUsers());
            //有效订单
            row4.getCell(2).setCellValue(businessData.getValidOrderCount());
            //平均客单价
            row4.getCell(4).setCellValue(businessData.getUnitPrice());

            //写入明细数据，下标从7开始，查询每一天的运营数据
            for (int i = 0; i < 30; i++) {
                LocalDate date = begin.plusDays(i);
                XSSFRow row7 = sheet.getRow(7 + i);
                //每一天的运营数据
                businessData = workspaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN), LocalDateTime.of(date, LocalTime.MAX));
                row7.getCell(1).setCellValue(date.toString());
                row7.getCell(2).setCellValue(businessData.getTurnover());
                row7.getCell(3).setCellValue(businessData.getValidOrderCount());
                row7.getCell(4).setCellValue(businessData.getOrderCompletionRate());
                row7.getCell(5).setCellValue(businessData.getUnitPrice());
                row7.getCell(6).setCellValue(businessData.getNewUsers());
            }
            //通过输出流将文件下载到客户端浏览器中
            out = response.getOutputStream();
            excel.write(out);
            out.flush();
        } catch (Exception e) {
            log.info("数据导出异常：{}",e.getMessage());
            e.printStackTrace();
            throw new OrderBusinessException(MessageConstant.DATA_EXPORT);
        }finally {
            //关闭资源
            try {
                out.close();
                excel.close();
            } catch (Exception e) {
                log.info("关闭资源失败：{}",e.getMessage());
                e.printStackTrace();
            }

        }
    }

    /**
     * 传入起始时间和终止时间，返回包含两者之间的LocalDate时间集合
     * @param begin
     * @param end
     * @return
     */
    private List<LocalDate> getDateList(LocalDate begin, LocalDate end){
        List<LocalDate> dateList = new ArrayList<>();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }
        return dateList;
    }


}
